import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
	
	private final static int port = 1234;
	private final static int sizeOfBuffer = 65536;
	
	public static void main(String[] args) throws InterruptedException {
		
		System.out.println("Welcome to Server side");
		
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(port);
			Socket client;
			while (true) {
				System.out.println();
				System.out.println("Waiting...");

				client = serverSocket.accept();
                DataInputStream data = new DataInputStream(client.getInputStream());
                String fileName = data.readUTF();
                long fileSize = data.readLong();
                FileOutputStream out = new FileOutputStream(fileName);
                
                System.out.println();
                System.out.println("Incoming file");
                System.out.println("Name of file: "+fileName);
                System.out.println("Size of file: "+fileSize+" bytes");
                
                byte[] buffer = new byte[sizeOfBuffer];
                int count;
				long total = fileSize;
				
				while (total > 0) {
					int bufferSize = (int) Math.min((long) sizeOfBuffer, total);
					count = data.read(buffer, 0, bufferSize);
					total -= count;
					out.write(buffer, 0, count);
				}
				
				System.out.println("File "+fileName+" was obtained");
                
				out.flush();
                out.close();
			}
			
		} catch (IOException e) {
			System.out.println(e.toString());
		} finally {
			try {
                serverSocket.close();
			} catch (IOException e) {
				System.out.println(e.toString());
			} catch (NullPointerException e) {
				System.out.println(e.toString());
			}
		}
	}
}
